'use strict';
 
var gulp = require('gulp');
var sass = require('gulp-sass');
var autoprefixer = require('autoprefixer');
var watchPath = require('gulp-watch-path');
var gutil = require('gulp-util');
var plumber = require('gulp-plumber');
var spritesmith = require('gulp.spritesmith');
var notify = require('gulp-notify');
var browserify = require('browserify');
var transform = require('vinyl-transform');
var glob = require("glob");
var babelify = require("babelify");
var eventStream = require("event-stream");
var watchify = require("watchify");
var sourcemaps = require("gulp-sourcemaps");
var source = require("vinyl-source-stream");
var buffer = require("vinyl-buffer");
var postcss = require('gulp-postcss');
// var clean = require('gulp-clean');
var browserSync = require('browser-sync').create();
var fs=require("fs");
var unzip=require("gulp-unzip");

var 
    del = require('del'),                   // 删除插件
    rev = require('gulp-rev'),              // 给文件增加md5后缀
    revCollector = require('gulp-rev-collector'),// 根据rev替换文件名
    htmlmin = require('gulp-htmlmin'),      // html压缩
    uglify = require('gulp-uglify'),        // js混淆压缩
    csso = require('gulp-csso'),            // 压缩Css
    cache = require('gulp-cache'),          // 缓存插件，使图片仅更新缓存中不一样的图片
    imagemin = require('gulp-imagemin'),    // 压缩图片
    runSequence = require('run-sequence');  // 改变任务优先级

var env = gulp.env;
var child = env._[0];
var path = child+'/';
var SRC_PATH = path+'src/js/';
var BUILD_PATH = path+'js/';
if(!child) {
    var err = new Error( 'you must input a channel name' );
    throw err;
}

var bundle = function (bundler, entryFilepath) {
  gutil.log(gutil.colors.green('Build ') + `${entryFilepath}`);

  return bundler.bundle()
    .on('error',function (e) {
      gutil.log(gutil.colors.red('Error ') + e.toString());
      gutil.log(gutil.colors.magenta('Position ') + JSON.stringify(e.loc));
    })
    .pipe(source(entryFilepath.replace(SRC_PATH, BUILD_PATH)))
    .pipe(buffer())
    .pipe(
      process.env.TYPE === "development" ?
        sourcemaps.init({loadMaps: true}) :
        gutil.noop()
    )
    .pipe(
      process.env.TYPE === "development" ?
        sourcemaps.write() :
        gutil.noop()
    )
    .pipe(gulp.dest("."));
};

var buildScripts = function (done, watch) {
  glob(`${SRC_PATH}/*.js`, function (err, files) {
    if (err) {
      done(err);
    }

    var tasks = files.map(function (entryFilepath) {
      var bundler = browserify({
        entries: [entryFilepath],
        debug: process.env.TYPE === "development",
        plugin: watch ? [watchify] : undefined
      })
        .transform(
          babelify,
          {
            presets: ["es2015","stage-0"]
          });

      var build = bundle.bind(this, bundler, entryFilepath);

      if (watch) {
        bundler.on("update", build);
      }

      return build();
    });

    return eventStream
      .merge(tasks)
      .on("end", done);
  });
};

// BROWSERIFY
gulp.task('js', function(done){
    buildScripts(done,true);
});


gulp.task('watch',function () {
    gulp.watch([path+'src/sass/**/*.scss','!'+path+'/src/sass/mixin/**','!'+path+'/src/sass/modules/**'], function (event) {
        var paths = watchPath(event, path+'src/sass/', path+'css/')

        gutil.log(gutil.colors.yellow(event.type) + ' ' + paths.srcPath)
        gutil.log(gutil.colors.green('Dist ') + paths.distPath)

        gulp.src([path+'src/sass/**/*.scss','!'+path+'src/sass/mixin/**','!'+path+'src/sass/modules/**'])
            .pipe(plumber()) // 兼容错误补丁
            .pipe(sass())
            .pipe(postcss([autoprefixer('>0.1%')]))
            .pipe(gulp.dest(paths.distDir))
    })
})

gulp.task('sass', function() {
    gulp.src([path+'src/sass/**/*.scss','!'+path+'/src/sass/mixin/**','!'+path+'/src/sass/modules/**'])
        .pipe(plumber()) // 兼容错误补丁
        .pipe(sass()) // sass语法
        .pipe(postcss([autoprefixer({"broswers":["> 0.1%","IOS 7","IOS8","last 2 versions"]})])) // autoprefix增加前缀，兼容> 1% 浏览器
        .pipe(gulp.dest(path+'css/')) // 输出文件夹
});


gulp.task(child, function () {
    if(child == 'build') {
        gulp.run('doBuild');
    } 
    else if(env.sprite) {
        gulp.run('sprite');
    }
    else {
        gulp.run('sass');
        gulp.run('js');
        gulp.run('watch');
    }
});
 
gulp.task('sprite', function () {
  var spriteData = gulp.src('./'+path+'src/images/*').pipe(spritesmith({
    imgName: 'sprite.png',
    imgPath: '../images/sprite.png',
    cssName: '../src/sass/mixin/sprite.scss',
    padding: 4,
    cssFormat: 'scss'
  }));
  return spriteData.pipe(gulp.dest(path+'images/'));
});


// js压缩，替换为md5文件名
gulp.task('jsmin', function() {
    return gulp.src(['*/**/*.js','!node_modules/**','!dist/**','!*/src/js/**'])
        .pipe(uglify())
        .pipe(rev())
        .pipe(gulp.dest('dist/'))
        .pipe(rev.manifest())
        .pipe(gulp.dest('rev/js'));
});

// css压缩，替换为md5文件名　
gulp.task('cssmin', function() {
    return gulp.src(['*/**/*.css','!dist/**','!node_modules/**','!**/src/**'])
        .pipe(csso({restructure: false}))
        .pipe(rev())
        .pipe(gulp.dest('dist/'))
        .pipe(rev.manifest())
        .pipe(gulp.dest('rev/css'));
});

// 替换html里的js和css链接，压缩html
gulp.task('rev',['cssmin','jsmin', 'imgCopy'],function(){
  return gulp.src(['rev/**/*.json','*/**/*.html', '!node_modules/**','!dist/**'])
    .pipe(revCollector())
    .pipe(htmlmin({
      removeComments: true,        // 去除注释
      collapseWhitespace: true,    // 去除空格 
      minifyJS: true,              // 优化行内JS
      minifyCSS: true             // 优化行内样式
    }))
    .pipe(gulp.dest('dist/'));
});

//复制图片
gulp.task('imgCopy', function(){
  var img_dir = ['*/images/**/*.{png,jpg,gif,ico,svg}','*/img/**/*.{png,jpg,gif,ico,svg}','!node_modules/**','!dist/**'];
  return gulp.src(img_dir, {base: '.'}).pipe(gulp.dest('dist/'));
});


// 图片压缩优化
gulp.task('imagemin', function() {
    var img_dir = ['*/images/**/*.{png,jpg,gif,ico,svg}','*/img/**/*.{png,jpg,gif,ico,svg}','!node_modules/**','!dist/**'];
    
    if(gulp.env.dir){
      img_dir = [
        gulp.env.dir + '/images/**/*' + '.{png,jpg,gif,ico,svg}',
        gulp.env.dir + '/img/**/*' + '.{png,jpg,gif,ico,svg}',
      ];
    }
    return gulp.src(img_dir, {base: '.'})
        .pipe(imagemin({
            optimizationLevel: 3, //类型：Number  默认：3  取值范围：0-7（优化等级）
            progressive: true //类型：Boolean 默认：false 无损压缩jpg图片
        }))
        .pipe(gulp.dest('dist/'));
});


// clean:bulid -- 2017-7-20 [之前方案]
// 删除dist里除了图片以外的资源
gulp.task('clean', function() {
    return del(['rev/**/*','dist/**/*.*', '!dist/mjb/**']);
});

gulp.task('copyTxt', function() {
  return gulp.src(['MP_verify_30OAAJHbFaYtPkgj.txt'])
    .pipe(gulp.dest('dist/'))
})

// clean:bulid  -- 2017-7-20 [最新方案]
// 删除dist目录所有资源，重新构建生成
// gulp.task("clean", function(){
//     return gulp.src('dist')
//            .pipe(clean());
// });


// 清除dist所有资源
gulp.task('cleanAll', function(callback) {
    del('dist')
    return cache.clearAll(callback);
});


gulp.task('doBuild', ['clean'], function(){
    // gulp.run('jsmin','cssmin','imagemin','rev');
  gulp.run('copyTxt', 'rev', 'handleMjb');
});


/**
 * 图片压缩
 * gulp smushit 
 * gulp smushit --dir dirname
 */
var smushit  = require('gulp-smushit');

gulp.task('smushit', function() {
  var img_dir = ['*/images/**/*.{png,jpg,gif,ico,svg}','*/img/**/*.{png,jpg,gif,ico,svg}','!node_modules/**','!dist/**'];
  
  if(gulp.env.dir){
    img_dir = [
      gulp.env.dir + '/images/*' + '.{png,jpg,gif,ico,svg}',
      gulp.env.dir + '/img/*' + '.{png,jpg,gif,ico,svg}',
    ];
  }

  return gulp.src(img_dir, {base: '.'})
      .pipe(smushit({
          verbose: true
      }))
      .pipe(gulp.dest('dist/'));
});

gulp.task('server', function(){
    browserSync.init({
      server: "./",
      directory: true
    });
    gutil.log('Start up successful!');
});

gulp.task('handleMjb', function() {
  fs.exists('zUpload/mjb.zip', function(exists) {
    if(exists) {
      gulp.src('zUpload/mjb.zip')
        .pipe(unzip())
        .pipe(gulp.dest('dist/mjb'))
    }
  })
})